﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Model;
using Utility;

namespace api
{
    public class JwtHelp
    {

        /// <summary>
        /// 生成JwtToken
        /// </summary>
        /// <param name="payload"></param>
        /// <returns></returns>
        public static string SetToken(IConfiguration _configuration, string userName)
        {
            double expireMinute = 30;
            double.TryParse(_configuration["AppSettings:JwtBearer:ExpireMinute"].ToString(), out expireMinute);

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,userName),
                new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
            };
            IdentityModelEventSource.ShowPII = true;
            var key = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(_configuration["AppSettings:JwtBearer:SecurityKey"]));

            var token = new JwtSecurityToken(
                issuer: _configuration["AppSettings:JwtBearer:Issuer"],
                audience: _configuration["AppSettings:JwtBearer:Audience"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(expireMinute),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            );
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
        /// <summary>
        /// 获取token信息
        /// </summary>
        /// <param name="HttpContext"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static ResultData<UserCache> GetToken(string token)
        {
            ResultData<UserCache> result = new ResultData<UserCache>();
            if (String.IsNullOrEmpty(token))
                result.code = ErrorCodeConst.TokenError;
            var userCache = RedisBase.Item_Get<UserCache>(token);
            if (userCache == null)
                result.code = ErrorCodeConst.TokenError;
            result.data = userCache;
            return result;
        }
        /// <summary>
        /// 清除token缓存信息
        /// </summary>
        /// <param name="HttpContext"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static void CleanToken(string token)
        {
            if (!String.IsNullOrEmpty(token))
                RedisBase.Item_Remove(token);
        }
        /// <summary>  
        /// DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name="time"> DateTime时间格式</param>  
        /// <returns>Unix时间戳格式</returns>  
        public static int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>  
        /// Unix时间戳转为C#格式时间  
        /// </summary>  
        /// <param name="timeStamp">Unix时间戳格式,例如1482115779</param>  
        /// <returns>C#格式时间</returns>  
        public static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

    }
}
